package com.way.filemanager.online;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.kanbox.api.Constant;
import com.kanbox.api.Kanbox;
import com.kanbox.api.KanboxException;
import com.kanbox.api.RequestListener;
import com.way.filemanager.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class SelectKanboxDirActivity extends Activity {

    private ListView mListView;
    private FileListAdapter mAdapter;
    private List<OnlineFileInfo> fileInfoList;
    private String type;
    private String sourcePath;
    private String fileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.file_list);
        sourcePath = getIntent().getExtras().getString("path");
        type = getIntent().getExtras().getString("type");
        fileName = getIntent().getExtras().getString("fileName");
        mListView = (ListView) findViewById(R.id.filelist_listview);
        //TODO modify this
        //mAdapter = new FileListAdapter(SelectKanboxDirActivity.this,null);
        mListView.setAdapter(mAdapter);
        fileInfoList = new ArrayList<OnlineFileInfo>();

        Kanbox.getFileList("", mRequestListener);

        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterview, View view,
                    int position, long l) {
                final OnlineFileInfo item = fileInfoList.get(position);
                String desPath = item.mFullPath;

                if (type.equals("move")) {
                    Kanbox.moveFile(sourcePath, desPath + "/" + fileName,
                            mRequestListener);
                } else if (type.equals("copy")) {
                    Kanbox.copyFile(sourcePath, desPath + "/" + fileName,
                            mRequestListener);
                }

            }
        });

    }

    private RequestListener mRequestListener = new RequestListener() {

        @Override
        public void onError(KanboxException error, int operationType) {
            Message msg = new Message();
            msg.what = HANDL_FAIL;
            msg.obj = error.getMessage() + error.getStatusCode();
            mHandler.sendMessage(msg);
        }

        @Override
        public void onComplete(String response, int operationType) {
            Message msg = new Message();
            switch (operationType) {
            case Constant.OP_GET_FILELIST:

                msg.what = GET_FILE_LIST;
                msg.obj = response;
                mHandler.sendMessage(msg);
                break;

            default:
                handleResponse(response);
                SelectKanboxDirActivity.this.finish();
                break;
            }

        }
    };

    private void handleResponse(String response) {
        Message msg = new Message();
        try {
            JSONObject sData = new JSONObject(response);
            String status = sData.getString("status");
            if (status.equals("ok")) {
                msg.what = HANDL_SUC;
                msg.obj = response;
                mHandler.sendMessage(msg);
            } else {
                msg.what = HANDL_FAIL;
                msg.obj = response;
                mHandler.sendMessage(msg);
            }
        } catch (JSONException e) {
            msg.what = HANDL_FAIL;
            msg.obj = e.toString();
            mHandler.sendMessage(msg);
        }

    }

    private FileListAdapterItemClick itemClicklistener = new FileListAdapterItemClick() {

        @Override
        public void onMoveClick(int position) {

        }

        @Override
        public void onMoreClick(int position) {

        }

        @Override
        public void onDeleteClick(int position) {

        }

        @Override
        public void onCopyClick(int position) {
        }
    };

    private static final int GET_FILE_LIST = 0;
    private static final int HANDL_SUC = 1;
    private static final int HANDL_FAIL = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case GET_FILE_LIST:
                try {
                    String jsonString = (String) msg.obj;
                    JSONObject response = new JSONObject(jsonString);

                    if (response.isNull("contents")) {
                        Toast.makeText(SelectKanboxDirActivity.this,
                                getString(R.string.empty_list),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        JSONArray contents = response.getJSONArray("contents");
                        for (int i = 0; i < contents.length(); i++) {
                            JSONObject item = contents.getJSONObject(i);
                            String fullPath = item.getString("fullPath");
                            String modificationDate = item
                                    .getString("modificationDate");
                            long fileSize = item.getLong("fileSize");
                            boolean isFolder = item.getBoolean("isFolder");
                            boolean isShared = item.getBoolean("isShared");
                            long creationDate = item.getLong("creationDate");

                            String path[] = fullPath.split("/");
                            String fileName = path[path.length - 1];

                            OnlineFileInfo fileitem = new OnlineFileInfo(fullPath,
                                    modificationDate, fileSize, isFolder,
                                    isShared, creationDate, fileName,0,false,false,null);
                            if (isFolder) {
                                fileInfoList.add(fileitem);
                            }

                        }
                        //mAdapter.setData(fileInfoList);
                        mAdapter.notifyDataSetChanged();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
            case HANDL_SUC:
                Toast.makeText(
                        SelectKanboxDirActivity.this,
                        getString(R.string.handl_suc) + "\n\n"
                                + (String) msg.obj, Toast.LENGTH_LONG).show();
                break;
            case HANDL_FAIL:
                Toast.makeText(
                        SelectKanboxDirActivity.this,
                        getString(R.string.handd_fail) + "\n\n"
                                + (String) msg.obj, Toast.LENGTH_LONG).show();
                break;

            default:
                break;
            }
        };
    };

}
